<template>
  <div v-title data-title="入库工作台">
    <!--  顶部当前扫描明细  -->
    <el-card class="box-card" shadow="hover">
      <div>
        <!--   扫描框   -->
        <el-input
          v-model="scanInput"
          :placeholder="scanInputPlaceholder"
          class="headerInputClass"
          @keydown.enter.native="enterScanInput()"
          ref="scanInputfocus"
          @focus="$event.currentTarget.select()"
          autofocus="autofocus"
        >
        </el-input>
      </div>
      <!--   扫描明细   -->
      <div>
        <el-descriptions class="margin-top" border :column="2">
          <el-descriptions-item
            label-class-name="my-label"
            content-class-name="my-content"
            label="任务编号"
          >
            {{ BillId }}
          </el-descriptions-item>
          <el-descriptions-item
            label-class-name="my-label"
            content-class-name="my-content"
            label="商品编码"
          >
            {{ CurrentGoods.SkuId }}
          </el-descriptions-item>
          <el-descriptions-item
            label-class-name="my-label"
            content-class-name="my-content"
            label="商品描述"
          >
            {{ CurrentGoods.SkuName }}
          </el-descriptions-item>
        </el-descriptions>
      </div>
    </el-card>
    <el-row :gutter="12" class="box-card card_box">
      <el-col :span="8">
        <el-card shadow="hover" class="box-card_detail imageClass">
          <div slot="header" class="clearfix">
            <span>商品信息</span>
          </div>
          <div class="imageClass">
            <el-image :src="CurrentGoods.ImgUrl" lazy></el-image>
            <!--支持本地图片下载-->
            <!--<el-image :src="localhostPath+CurrentGoods.ImgUrl" lazy></el-image>-->
          </div>
        </el-card>
      </el-col>
      <!--   本次上架明细   -->
      <el-col :span="6">
        <el-card shadow="hover" class="box-card_detail">
          <div slot="header" class="clearfix">
            <span>数量信息</span>
          </div>
          <div>
            <div class="ItemNumInfo" @click="clickCalculator()">
              {{ scansNum }}/{{ scansTotalNum }}
            </div>
            <br /><br />
            <div class="ItemNumlabel">扫描数量/上架总数量</div>
            <div class="ItemNumInfoDetail">单位：{{ CurrentGoods.unit }}</div>
            <div class="ItemNumInfoDetail">
              规格：<span>{{ CurrentGoods.spec }}</span>
            </div>
          </div>
        </el-card>
      </el-col>
      <!--   上架列表  已扫描的货物明细   -->
      <el-col :span="10">
        <el-card shadow="hover" class="box-card_detail paddingStyle">
          <div slot="header" class="clearfix">
            <span>上架列表</span>
          </div>
          <el-table
            :data="ScanRecord"
            height="41vh"
            border
            style="width: 100%; font-size: calc(100vh - 98.5vh)"
          >
            <el-table-column
              align="center"
              type="index"
              width="80"
            ></el-table-column>
            <el-table-column
              align="center"
              prop="SkuId"
              label="商品编码"
            ></el-table-column>
            <el-table-column
              align="center"
              prop="QtyIn"
              label="扫描数量"
            ></el-table-column>
            <el-table-column
              align="center"
              prop="LocationId"
              label="库位"
            ></el-table-column>
            <el-table-column
              align="center"
              prop="CID"
              label="容器号"
            ></el-table-column>
            <el-table-column
              align="center"
              prop="BoxCode"
              label="容器号"
            ></el-table-column>
          </el-table>
        </el-card>
      </el-col>
    </el-row>
    <el-card shadow="never" class="card_button">
      <!--			<el-button @click='$router.push(`/index`)' type="warning">返回主页</el-button>-->
      <!--      <el-button type="danger" @click='scanInputMethod("OrderID");audioPlay("ok")'>重置工作台</el-button>-->
      <el-button @click="PrintBarcode()">打印条码</el-button>
      <el-button @click="BindEmptyCIDVisible = true">空托上架</el-button>
      <el-button type="danger" @click="EmptyContainer()">清空容器</el-button>
      <el-button type="danger" @click="EmptyBox()">清空扫描</el-button>
      <!--      <el-button type="danger" @click='CallEmptyCID()'>呼叫空托</el-button>-->
      <!--      <el-button type="primary" class='buttonClass' @click='QuickLaunchVisible=true'-->
      <!--                 :loading="submit.loading">快速上架</el-button>-->
      <el-button
        type="primary"
        class="buttonClass"
        @click="CompleteTaskButton()"
        :loading="submit.loading"
        :disabled="disabledFlag"
        >绑托上架
      </el-button>
      <span style="margin-left: 30px"
        >工作台: {{ UserInfo.WbInfo.WbName }}</span
      >
    </el-card>
    <!-- 呼叫空托 数字输入  -->
    <el-dialog :visible.sync="CalculatorDialogVisible" width="30%">
      <Calculator v-on:clickCardOk="clickCardOk" />
    </el-dialog>
    <!-- 完成输入 -->
    <el-dialog
      title="绑托上架"
      :visible.sync="CommitVisible"
      width="30%"
      class="dialog_commit"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <el-form label-width="12vh" :model="CommitFrom">
        <el-form-item label="托盘编码">
          <el-input
            v-model="CommitFrom.CID"
            placeholder="请扫描托盘编码"
            ref="COMMITCID"
            @keydown.enter.native="
              this.$nextTick(() => {
                this.$refs.COMMITLoc.focus();
              })
            "
          ></el-input>
        </el-form-item>
        <el-form-item label="库位编码">
          <el-input
            ref="COMMITLoc"
            v-model="CommitFrom.LocationId"
            placeholder="请扫描库位编码"
            @keydown.enter.native="CompleteTask()"
          ></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button
          @click="
            CommitVisible = false;
            CommitFrom = { CID: '', LocationId: '' };
          "
          >取 消</el-button
        >
        <el-button type="primary" @click="CompleteTask()">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 快速上架 -->
    <el-dialog
      title="快速上架"
      :visible.sync="QuickLaunchVisible"
      width="30%"
      class="dialog_commit"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <el-form label-width="12vh" :model="QuickCommitFrom">
        <el-form-item label="托盘编码">
          <el-input
            v-model="QuickCommitFrom.CID"
            placeholder="请扫描托盘编码"
            ref="QuickCommitCID"
            @keydown.enter.native="
              this.$nextTick(() => {
                this.$refs.QuickCommitLocationId.focus();
              })
            "
          ></el-input>
        </el-form-item>
        <el-form-item label="库位编码">
          <el-input
            ref="QuickCommitLocationId"
            v-model="QuickCommitFrom.LocationId"
            placeholder="请扫描库位编码"
            @keydown.enter.native="QuickCompleteTask()"
          ></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button
          @click="
            QuickLaunchVisible = false;
            QuickCommitFrom = { CID: '', LocationId: '' };
          "
          >取 消</el-button
        >
        <el-button type="primary" @click="QuickCompleteTask()">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 空托上架 -->
    <el-dialog
      title="空托上架"
      width="30%"
      class="dialog_commit"
      :visible.sync="BindEmptyCIDVisible"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <el-form label-width="12vh" :model="BindEmptyCID">
        <el-form-item label="托盘编码">
          <el-input
            v-model="BindEmptyCID.CID"
            placeholder="请扫描托盘编码"
            ref="BindEmptyCIDRef"
            @keydown.enter.native="
              this.$nextTick(() => {
                this.$refs.BindEmptyCIDLocationId.focus();
              })
            "
          ></el-input>
        </el-form-item>
        <el-form-item label="库位编码">
          <el-input
            ref="BindEmptyCIDLocationId"
            v-model="BindEmptyCID.LocationId"
            placeholder="请扫描库位编码"
            @keydown.enter.native="BindEmptyCIDCommit()"
          ></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button
          @click="
            BindEmptyCIDVisible = false;
            BindEmptyCID = { CID: '', LocationId: '' };
          "
          >取 消</el-button
        >
        <el-button type="primary" @click="BindEmptyCIDCommit()"
          >确 定</el-button
        >
      </span>
    </el-dialog>
    <!--    提示音  -->
    <audioPaly :audioValue="audioPaly"></audioPaly>
  </div>
</template>

<script>
import Arithmetic from '@/utils/ArithmeticMethod.js'
import TrayGridVerification from '@/utils/public_function.js'
import {
  PrevLoading
} from '@/utils/loading.js'
import {
  GETWarehousingTaskInfo,
  GETWarehousingTaskScannedInfo, //获取扫描
  PUTWarehousingTaskScannedInfo, //添加扫描
  DELETEWarehousingTaskScannedInfo, //删除扫描
  POSTWarehousingTaskScannedInfo, //完成扫描
  GetCIDInfo,
  EmptyCIDBind,
  EmptyCID,
  postFastWarehousing, PTL_ACTION //快速入库
} from '@/api/api.js'
import Calculator from '@/components/pluginunit/Calculator.vue'
import audioPaly from '@/components/pluginunit/audioPaly.vue'
import { createSocket } from "@/utils/WebSocket";

export default {
  name: 'WarehousingOPT',
  props: ['searchVal'],
  components: {
    Calculator,
    audioPaly
  },
  data () {
    return {
      submit: {
        loading: false,
      },
      QuickCommitFrom: {
        CID: '',
        LocationId: ''
      },
      bindCIDFrom: {
        CID: '',
        LocationId: ''
      },
      BindEmptyCID: {
        CID: '',
        LocationId: ''
      },
      bindCIDFlag: true,
      disabledFlag: true,
      audioPaly: '',
      // 扫描框内容
      scanInput: '',
      // 扫描框当前扫描类型
      scanType: 'OrderID',
      scanInputPlaceholder: '',
      scanInputFlag: true,
      scanInputType: {
        'OrderID': '请扫描单号.....',
        'SkuID': '请扫描商品编码.....',
        'CID': '请输入数量后，扫描容器编码.....',
      },
      // 当前扫描商品信息（显示）
      CurrentGoods: {
        BillId: '',
        SkuId: '',
        SkuName: '',
        ImgUrl: ''
      },
      BillId: '',
      // 全部应扫描商品
      AllGoods: [],
      // 已扫描商品
      ScannedGoods: [],
      // 扫描记录
      ScanRecord: [],
      // 完成任务或者呼叫空托提交的扫描记录
      CommitScanRecord: [],
      // 全部入库数（不考虑商品种类）
      ScanAllCount: 0.0,
      // 当前扫描数
      ScanCurrentCount: 0.0,
      // 已扫描商品数（不考虑商品种类）
      ScanGoodCount: 0.0,
      // 页面显示应扫描数
      scansTotalNum: 0.0,
      // 页面显示当前已扫描数
      scansNum: 0.0,
      // 输入框标识
      CalculatorDialogVisible: false,
      // 绑托上架标识
      CommitVisible: false,
      // 快速上架标识
      QuickLaunchVisible: false,
      // 空托绑定标识
      BindEmptyCIDVisible: false,
      localhostPath: "",
      UserInfo: {
        WbInfo: {
          WbName: ''
        }
      },
      CommitFrom: {
        CID: '',
        LocationId: ''
      },
      WarehouseId: '',
      StorerId: '',
      // 灯 所需参数
      getSocketData: null,
      url: 'ws://localhost:1234/webSocket',
      ptl_url: 'ws://localhost:13145/Ptl',
      ColorEnum: {
        red: 1,
        green: 2,
        blue: 3,
        yellow: 4,
        pink: 5,
        cyan: 6,
        white: 7
      }
      //  结束
    }
  },
  created () {
    window.removeEventListener('onmessageWS', this.getSocketData);
    this.UserInfo = JSON.parse(sessionStorage.getItem('userInfo'))
    this.scanInputMethod(this.scanType)
    this.init()
    this.getUrlPath()
  },
  methods: {
    GETTaskInfo (value) {
      const params = {
        UserId: this.UserInfo.UserId,
        BillId: value,
        WbId: this.UserInfo.WbInfo.WbId,
        time: Date.parse(new Date())
      }
      GETWarehousingTaskInfo(params).then(res => {
        const result = res.data.data
        if (res.data.code == 0 && result.length != 0) {
          // 收集全部扫描数
          result.forEach((item, index, arr) => {
            item.UpcCodes = item.UpcCodes.split(',')
            let getLocation = item.UpcCodes.indexOf("");
            item.UpcCodes.splice(getLocation, 1);
            item.UpcCodes.push(item.SkuId)
            this.AllGoods.push(item)
          })
          console.log('AllGoods', this.AllGoods);
          this.BillId = value
          this.StorerId = result[0].StorerId
          this.WarehouseId = result[0].WarehouseId
          // 获取已扫描数据
          this.GETTaskScanedInfo(value)
        } else {
          this.audioPlay('notexist')
          this.$message({
            message: res.data.message,
            type: 'error'
          });
        }
      }).catch(error => {
        this.audioPlay('error')
        throw error
      })
    },
    GETTaskScanedInfo (value) {
      const params = {
        UserId: this.UserInfo.UserId,
        BillId: value,
        time: Date.parse(new Date())
      }
      GETWarehousingTaskScannedInfo(params).then(res => {
        const result = res.data.data
        if (res.data.code == 0) {
          // 收集已扫描数
          // this.ScannedGoods = result
          result.forEach((item, index, arr) => {
            item.UpcCodes = item.UpcCodes.split(',')
            let getLocation = item.UpcCodes.indexOf("");
            item.UpcCodes.splice(getLocation, 1);
            item.UpcCodes.push(item.SkuId)
            this.ScannedGoods.push(item)
            this.ScanRecord.push(item)
          })
          this.SummarizeTaskInfo('init')
          this.scanInputMethod('SkuID')
          this.audioPlay('ok')
        } else {
          this.$message({
            message: res.data.message,
            type: 'warning'
          });
        }
      }).catch(error => {
        throw error
      })
    },
    // 输入数量呼叫空托
    CallEmptyCID () {
      this.$prompt('请输入要呼叫的空托数', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputPattern: /^[1-9]\d*$/,
        inputErrorMessage: '请输入正确的数字'
      }).then(({ value }) => {
        const params = {
          "CIDNumber": parseInt(value),
          "WbId": this.UserInfo.WbInfo.WbId,
          "UserId": this.UserInfo.UserId
        }
        EmptyCID(params).then(res => {
          const result = res.data.data
          if (res.data.code == 0) {
            this.$message({
              message: res.data.message,
              type: 'success'
            });
            this.audioPlay('success')
          } else {
            this.$message({
              message: res.data.message,
              type: 'error'
            });
            this.audioPlay('error')
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '取消输入'
        });
      });
    },
    //快速上架
    QuickCompleteTask () {
      if (this.QuickCommitFrom.CID == '' || this.QuickCommitFrom.LocationId == '') {
        this.$message({
          message: '请输入完整的快速上架信息',
          type: 'warning'
        });
      }
      const params = {
        "CID": this.QuickCommitFrom.CID,
        "LocationId": this.QuickCommitFrom.LocationId,
        "WbId": this.UserInfo.WbInfo.WbId,
        "UserId": this.UserInfo.UserId
      }
      postFastWarehousing(params).then(res => {
        const result = res.data.data
        if (res.data.code == 0) {
          this.$message({
            message: res.data.message,
            type: 'success'
          });
          this.QuickCommitFrom = {
            CID: '',
            LocationId: ''
          }
          this.audioPlay('success')
        } else {
          this.$message({
            message: res.data.message,
            type: 'error'
          });
          this.audioPlay('error')
        }
      }).catch(error => {
        throw error
      })
    },
    //空托上架
    BindEmptyCIDCommit () {
      if (this.BindEmptyCID.CID == '' || this.BindEmptyCID.LocationId == '') {
        this.$message({
          message: '请输入完整的空托上架信息',
          type: 'warning'
        });
      }
      const params = {
        "CID": this.BindEmptyCID.CID,
        "LocationId": this.BindEmptyCID.LocationId,
        "WbId": this.UserInfo.WbInfo.WbId,
        "UserId": this.UserInfo.UserId
      }
      EmptyCIDBind(params).then(res => {
        if (res.data.code == 0) {
          this.$message({
            message: res.data.message,
            type: 'success'
          });
          this.BindEmptyCID = {
            CID: '',
            LocationId: ''
          }
          this.audioPlay('success')
        } else {
          this.$message({
            message: res.data.message,
            type: 'error'
          });
          this.audioPlay('error')
        }
      }).catch(error => {
        throw error
      })
    },
    CompleteTaskButton () {
      if (this.scanType == 'OrderID') {
        this.audioPlay('error')
        this.$message({
          message: "请确定当前流程是否可以提交",
          type: 'error'
        });
        return
      }
      this.CommitVisible = true
      this.$nextTick(() => {
        this.$refs.COMMITCID.focus()
      })
    },
    // 完成按钮
    CompleteTask () {
      this.submit.loading = true
      if (this.CommitFrom.LocationId == '') {
        this.audioPlay('error')
        this.$alert('请确认是否扫描库位编码', '警告', {
          confirmButtonText: '确定',
        });
        return
      }
      if (this.CommitFrom.CID == '') {
        this.audioPlay('error')
        this.$alert('请确认扫描托盘编码是否正确', '警告', {
          confirmButtonText: '确定',
        });
        return
      }
      const params = {
        UserId: this.UserInfo.UserId,
        BillId: this.BillId,
        CID: this.CommitFrom.CID,
        LocationId: this.CommitFrom.LocationId,
        time: Date.parse(new Date())
      }
      POSTWarehousingTaskScannedInfo(params).then(res => {
        const result = res.data.data
        if (res.data.code == 0) {
          this.$message({
            message: res.data.message,
            type: 'success'
          });
          this.scanInputMethod('SkuID')
          this.ScanRecord.forEach((item, index, arr) => {
            if (TrayGridVerification.SameCID(this.CommitFrom.CID, item.CID)) {
              this.$set(this.ScanRecord[index], 'LocationId', JSON.stringify(
                // 此方法才能更新视图
                this.CommitFrom.LocationId).replaceAll('"', ''));
            }
          })
          this.CompleteOrder()
          this.CommitFrom = {
            CID: '',
            LocationId: ''
          }
          this.$nextTick(() => {
            this.$refs.COMMITCID.focus()
          })
          this.audioPlay('success')
        } else {
          this.audioPlay('error')
          this.$alert(res.data.message, '警告', {
            confirmButtonText: '确定',
            callback: action => {
              this.CommitFrom = {
                CID: '',
                LocationId: ''
              }
            }
          });
        }
      }).catch(error => {
        throw error
      })
      this.submit.loading = false
    },
    CompleteOrder () {
      let allScanCount = 0.0;
      let allCount = 0.0;
      this.ScanRecord.forEach(item => {
        allScanCount = Arithmetic.accAdd(allScanCount, item.QtyIn)
      })
      this.AllGoods.forEach(item => {
        allCount = Arithmetic.accAdd(allCount, item.QtyPlan)
      })
      console.log('this.ScanRecord', this.ScanRecord)
      for (var i = 0; i < this.ScanRecord.length; i++) {
        if ((this.ScanRecord[i].LocationId == undefined || this.ScanRecord[i].LocationId == null || this
          .ScanRecord[i].LocationId == "" || this.ScanRecord[i].LocationId == '')) {
          return
        }
      }
      if (allCount != allScanCount) {
        return
      }
      this.scanInputMethod('OrderID')
      this.CommitVisible = false
    },
    // 清空扫描
    EmptyBox () {
      if (this.submit.loading) {
        this.$message({
          message: "请等待当前任务操作完成",
          type: 'error'
        });
        this.audioPlay('error')
        return
      }
      if (this.StorerId == '' || this.BillId == '') {
        this.audioPlay('error')
        this.$message({
          message: "请确认要订单信息",
          type: 'error'
        });
        return
      }
      this.$confirm('<span style="font-size:20px">是否清空扫描记录</span>', '清空扫描', {
        confirmButtonText: '确定清空',
        cancelButtonText: '取消清空',
        dangerouslyUseHTMLString: true,
        type: 'warning'
      }).then(() => {
        const params = {
          DelType: 'Box',
          UserId: this.UserInfo.UserId,
          BillId: this.BillId,
          StorerId: this.StorerId,
          time: Date.parse(new Date())
        }
        DELETEWarehousingTaskScannedInfo(params).then(res => {
          var result = res.data
          if (result.code == 0) {
            this.$message({
              message: '清空容器成功',
              type: 'success'
            });
            this.audioPlay('success')
            this.scanInputMethod('OrderID')
          } else {
            this.audioPlay('error')
            this.$message({
              message: res.data.message,
              type: 'error'
            });
          }
        });
      }).catch((error) => {
        console.log(error)
        this.$message({
          type: 'info',
          message: '清空操作已取消'
        });
      });
    },
    getUrlPath () {
      let wPath = window.document.location.href;
      // 获取当前页面主机地址之后的目录，如：/admin/index
      let pathName = this.$route.path;
      let pos = wPath.indexOf(pathName);
      // 获取主机地址，如：http://localhost:8080
      this.localhostPath = wPath.substring(0, pos).split('#')[0];
      this.localhostPath = this.localhostPath.substring(0, this.localhostPath.length - 1);
    },
    // 清空容器
    EmptyContainer () {
      if (this.submit.loading) {
        this.audioPlay('error')
        this.$message({
          message: "请等待当前任务操作完成",
          type: 'error'
        });
        return
      }
      if (this.StorerId == '' || this.BillId == '') {
        this.audioPlay('error')
        this.$message({
          message: "请确认要清空的订单信息",
          type: 'error'
        });
        return
      }
      this.$prompt('<span style="font-size:25px">请扫描容器编码</span>', '清空容器', {
        confirmButtonText: '确定清空',
        cancelButtonText: '取消清空',
        dangerouslyUseHTMLString: true,
        center: false
      }).then(({
        value
      }) => {
        const params = {
          DelType: 'Container',
          UserId: this.UserInfo.UserId,
          BillId: this.BillId,
          CID: value,
          StorerId: this.StorerId,
          time: Date.parse(new Date())
        }
        DELETEWarehousingTaskScannedInfo(params).then(res => {
          var result = res.data
          if (result.code == 0) {
            this.$message({
              message: '清空容器成功',
              type: 'success'
            });
            for (var i = this.ScanRecord.length - 1; i >= 0; i--) {
              if (value == this.ScanRecord[i].CID || value == this.ScanRecord[i].BoxCode) {
                this.ScanRecord.splice(i, 1)
              }
            }
            this.audioPlay('success')
            this.SummarizeTaskInfo('init')
          } else {
            this.audioPlay('error')
            this.$message({
              message: res.data.message,
              type: 'error'
            });
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '清空操作已取消'
        });
      });
    },
    // 扫描SKU
    ScanSkuInfo (value) {
      var scanCount = 0.0
      var currinfo = {}

      this.AllGoods.forEach(items => {
        if (items.UpcCodes.indexOf(value) != -1) {
          scanCount = Arithmetic.accAdd(scanCount, items.QtyPlan)
          currinfo = items
        }
      })
      this.ScanRecord.forEach(item => {
        // console.log(item)
        if (item.UpcCodes.indexOf(value) != -1) {
          // (item.SkuId == value) {
          scanCount = Arithmetic.accSub(scanCount, item.QtyIn)
        }
      })
      if (parseFloat(scanCount) == 0.0) {
        this.audioPlay('error')
        this.$message({
          message: 'SKU已经全部扫描完成或者本次订单不包含此类SKU',
          type: 'error'
        });
        return
      }
      this.CurrentGoods = JSON.parse(JSON.stringify(currinfo))
      console.log(this.localhostPath)
      console.log(this.localhostPath + this.CurrentGoods.ImgUrl)
      this.SummarizeTaskInfo(value)
      this.scanInputMethod('CID')
      this.audioPlay('ok')
    },
    VerificationCID (value) {
      if (parseFloat(this.CurrentGoods.QtyIn) == 0.0 || parseFloat(this.scansNum) == 0.0) {
        this.audioPlay('error')
        this.$message({
          message: '请输入正确入库数量',
          type: 'error'
        });
        return
      }
      const params = {
        UserId: this.UserInfo.UserId,
        CID: value,
        time: Date.parse(new Date())
      }
      GetCIDInfo(params).then(res => {
        const result = res.data.data
        if (result.length > 0 && res.data.code == 0) {
          if (result[0].used > 0) {
            this.audioPlay('error')
            this.$message({
              message: '托盘已经被使用',
              type: 'error'
            });
            return
          }
          if (parseFloat(result[0].stock) > 0.0) {
            this.audioPlay('error')
            this.$message({
              message: '托盘存在库存',
              type: 'error'
            });
            return
          }
          this.ScanCID(value)
        } else {
          this.audioPlay('notexist')
          this.$message({
            message: '托盘不存在',
            type: 'error'
          });
        }
      })
    },
    // 扫描托盘操作
    ScanCID (value) {
      this.CurrentGoods.CID = value
      this.CurrentGoods.UserId = this.UserInfo.UserId
      this.CurrentGoods.WbId = this.UserInfo.WbInfo.WbId
      this.CurrentGoods.time = Date.parse(new Date())
      const params = this.CurrentGoods
      PUTWarehousingTaskScannedInfo(params).then(res => {
        const result = res.data.data
        if (res.data.code == 0) {
          console.log(result)
          if (result[0].issucess == 1) {
            if (TrayGridVerification.IsGrid(this.CurrentGoods.CID, true)) {
              this.CurrentGoods.BoxCode = value
              this.CurrentGoods.CID = value.split('-')[0]
            } else {
              this.CurrentGoods.BoxCode = ''
            }
            this.ScanRecord.push(JSON.parse(JSON.stringify(this.CurrentGoods)))
            this.CommitScanRecord.push(JSON.parse(JSON.stringify(this.CurrentGoods)))
            this.scanInputMethod('SkuID')
            this.SummarizeTaskInfo('init')
            this.CurrentGoods = {}
            this.disabledFlag = false
            this.audioPlay('ok')
          } else {
            this.audioPlay('error')
            this.$message({
              message: result[0].errmsg,
              type: 'error'
            });
          }
        } else {
          this.audioPlay('error')
          this.$message({
            message: res.data.message,
            type: 'error'
          });
        }
      }).catch(error => {
        throw error
      })
    },
    // 声音
    audioPlay (value) {
      this.audioPaly = value
      setTimeout(() => {
        this.audioPaly = ''
      }, 1500)
    },
    // 亮灯
    async PTL_Lighting (LocationId, Color) {
      const params = {
        "Id": new Date().getTime().toString(),
        "Type": "PTL_Lighting",
        "Data": {
          "Tag": LocationId,
          "Num": this.CurrentGoods.QtyPlan.toString(),
          "Mode": "1",
          "Color": Color,
          "Updown": "2",
          "Locator": "",
          "Message": this.CurrentGoods.SkuId,
          "PressOff": "1"
        }
      }
      this.PTLSendCommand(this.ptl_url, params)
    },
    // 关灯
    async PTL_Close (LocationId) {
      const params = {
        "Id": new Date().getTime().toString(),
        "Type": "PTL_Close",
        "Data": {
          "Tag": LocationId
        }
      }
      this.PTLSendCommand(this.ptl_url, params)
    },
    // 拍灯-灭灯
    async PTL_OFF (LocationId) {
      const params = {
        "LocationId": LocationId
      }
      PTL_ACTION(params).then(res => {
        const results = res.data.data
        if (res.data.code === 0) {
          var result = results[0]
          if (result.issuccess === 0) {
            this.PTL_Close(LocationId)
          }
          if (result.issuccess === 11) {
            this.PTL_Lighting(LocationId, this.ColorEnum.green)
            if (!result.errmsg === '') {
              this.$message({
                type: 'error',
                message: result.errmsg && ''
              })
            }
          }
          if (result.issuccess === 10) {
            this.PTL_Lighting(LocationId, this.ColorEnum.blue)
          }
        } else {
        }
      }).catch(error => {
        throw error
      })
      this.scanInputMethod('OrderID', false)
      this.GETTaskInfo()
      //this.PTLSendCommand(this.ptl_url, params)
    },
    // 异步登录打印机,灯
    async init () {
      var url = "ws://localhost:13145/Login?UserId=" + this.UserInfo.UserId;
      var command = {
        RemoteUrl: this.UserInfo.RemoteUrl,
      };
      this.SendCommand(url, command);
      createSocket(this.ptl_url)
      const getsocketData = e => {  // 创建接收消息函数
        const data = JSON.parse(e && e.detail.data)
        console.log(data)
        if (data.Type === 'PTL_Lighting') {
          console.log('PTL_Lighting', data)
        }
        else if (data.Type === 'PTL_Close') {
          console.log('PTL_Close', data)
        }
        else if (data.Type === 'PTL_OFF') {
          if (this.QuickLaunchVisible == true) {
            this.QuickCompleteTask()
          } else {
            this.CompleteTaskButton(data.Data.Tag)
          }
        }
        else {
          this.$message({
            type: 'error',
            message: 'WET消息错误'
          });
        }
      }
      // 注册监听事件
      window.addEventListener('onmessageWS', getsocketData)
    },
    // 打印条码
    PrintBarcode () {
      // 存储区不能为空，且需要扫描指定订单后才能打印条码。
      if (this.StorerId == '' || this.scanType == 'OrderID') {
        this.audioPlay('error')
        this.$message({
          type: 'info',
          message: '请先扫描要入库的订单信息'
        });
        return
      }

      this.$prompt('请输入要打印的商品编码', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
      }).then(({
        value
      }) => {
        var url = "ws://localhost:13145/Print?UserId=" + this.UserInfo.UserId;
        var command = [{
          TaskId: value + '_' + Date.parse(new Date()).toString(),
          WarehouseId: this.WarehouseId,
          StorerId: this.StorerId,
          MenuId: "M222",
          Action: "Print",
          DataSourceParameter: "{'StorerId':'" + this.StorerId + "',SkuId:'" + value + "'}"
        }];
        this.SendCommand(url, command);
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '打印已取消'
        });
      });
    },
    SendCommand (url, command) {
      var ws = new WebSocket(url);
      ws.onopen = function () {
        ws.send(JSON.stringify(command));
      };
      ws.onmessage = function (e) {
        //alert(e.data);
        console.log(e.data);
        document.getElementById('response').innerText = e.data;
      };
      ws.onclose = function () {
        //alert("close");
      };
    },
    PTLSendCommand (url, command) {
      var ws = new WebSocket(url);
      ws.onopen = function () {
        console.log('发送参数：', command);
        ws.send(JSON.stringify(command));
      };
      ws.onmessage = function (e) {
        console.log('返回：', e.data);
        const datas = e.data
        if (datas.code !== 0) {
          this.$message({
            type: 'error',
            message: datas.Message
          });
        }
      };
      ws.onclose = function () {
        //alert("close");
      };
    },
    enterScanInput () {
      if (!this.checkInputEmpty()) {
        return
      }
      const value = this.scanInput.replace(/\ +/g, "").replace(/[\r\n]/g, "");
      this.scanInput = value
      // 订单信息
      if (this.scanType == 'OrderID') {
        this.GETTaskInfo(value)
      }
      // SKU编码
      else if (this.scanType == 'SkuID') {
        this.ScanSkuInfo(value)
      }
      // 托盘信息
      else if (this.scanType == 'CID') {
        this.VerificationCID(value)
      } else {
        this.audioPlay('error')
        this.$message({
          message: '系统错误，请刷新当前页面',
          type: 'error'
        });
        return
      }
      this.$nextTick(() => {
        this.$refs.scanInputfocus.focus()
      })
    },
    // 判断应扫描数是否大于等于输入扫描数
    clickCardOk (value) {
      if (parseFloat(this.scansTotalNum) >= parseFloat(value) && parseFloat(value) >= 0.0) {
        this.scansNum = parseFloat(value)
        this.CurrentGoods.QtyIn = parseFloat(value)
        this.CalculatorDialogVisible = false
      } else {
        this.audioPlay('error')
        this.$message({
          message: '扫描数不能大于应扫描总数，且为正数',
          type: 'warning'
        });
      }
    },
    // 屏幕显示计算 Value 如果为init为计算初始化数据。
    SummarizeTaskInfo (value) {
      var allcount = 0.0
      var allscancount = 0.0
      var currentRecord = 0.0
      if (value == 'init') {
        this.AllGoods.forEach(item => {
          // 计算全部扫描数
          allscancount = Arithmetic.accAdd(allscancount, item.QtyPlan)
        })
        // this.ScannedGoods.forEach(item => {
        // 	// 计算已扫描数量、
        // 	allcount += item.QtyIn
        // })
        this.ScanRecord.forEach(item => {
          // 计算本次已扫描数
          currentRecord = Arithmetic.accAdd(currentRecord, item.QtyIn)
        })
        this.ScanAllCount = allscancount
        this.ScanGoodCount = Arithmetic.accAdd(allcount, currentRecord)
        // 将全部扫描数输出到屏幕
        this.scansTotalNum = this.ScanAllCount
        // 把已扫描数量输出
        this.scansNum = this.ScanGoodCount
        // &&currentRecord!=allscancount
        this.disabledFlag = parseFloat(currentRecord) <= 0.0;
        return
      }
      this.AllGoods.forEach(item => {
        if (item.UpcCodes.indexOf(value) != -1) {
          // 计算全部扫描数
          allscancount = Arithmetic.accAdd(allscancount, item.QtyPlan)
        }
      })
      // this.ScannedGoods.forEach(item => {
      // 	if (item.SkuId == value) {
      // 		// 计算已扫描数量
      // 		allcount += item.QtyIn
      // 	}
      // })
      this.ScanRecord.forEach(item => {
        if (item.UpcCodes.indexOf(value) != -1) {
          // 计算本次已扫描数
          currentRecord = Arithmetic.accAdd(currentRecord, item.QtyIn)
        }
      })
      // 将全部扫描数输出到屏幕
      this.scansTotalNum = Arithmetic.accSub(Arithmetic.accSub(allscancount, allcount), currentRecord)
      // 把已扫描数量输出
      this.scansNum = 0.0
    },
    // 改变扫描框
    scanInputMethod (newType) {
      if (this.scanInputType[newType] === undefined) {
        return
      }
      if (newType == 'OrderID') {
        this.CurrentGoods = {}
        this.BillId = ''
        // 全部应扫描商品
        this.AllGoods = []
        // 已扫描商品
        this.ScannedGoods = []
        // 显示扫描记录
        this.ScanRecord = []
        // 完成任务或者呼叫空托提交的扫描记录
        this.CommitScanRecord = []
        // 全部入库数（不考虑商品种类）
        this.ScanAllCount = 0.0
        // 当前扫描数
        this.ScanCurrentCount = 0.0
        // 已扫描商品数（不考虑商品种类）
        this.ScanGoodCount = 0.0
        // 页面显示应扫描数
        this.scansTotalNum = 0.0
        // 页面显示当前已扫描数
        this.scansNum = 0.0
        this.WarehouseId = ''
        this.StorerId = ''
      }
      this.scanInput = ''
      this.scanInputPlaceholder = this.scanInputType[newType];
      this.scanType = newType;
    },
    // 点击计算器验证
    clickCalculator () {
      if (this.scanType == 'CID') {
        this.CalculatorDialogVisible = true
        return
      }
      this.audioPlay('error')
      this.$message({
        message: '获取订单并且扫描SKU后才能对数量进行操作',
        type: 'error'
      });
    },
    // 检查输入扫描框是否为空
    checkInputEmpty () {
      if (this.scanInput == '') {
        this.audioPlay('error')
        this.$message({
          message: '请检查扫描框内容是否为空',
          type: 'error'
        });
        return false
      }
      return true
    },
  },
  destroyed () {
    //移除监听器页面销毁时，移除监听器，这样就不会导致重复监听。
    window.removeEventListener('onmessageWS', this.getSocketData);
  },
  watch: {
    searchVal: function (val) {
      console.log(val); // 接收父组件的值
      this.WindowsSize = val;
    }
  },
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style>
.my-label {
  font-size: 1.3vw;
  width: 10vw;
  /* font-weight: 550 !important; */
  text-align: center !important;
  color: #000000 !important;
}

.my-content {
  color: #000000;
  font-size: 1.3vw;
  /* font-weight: 550 !important; */
  width: 40vw;
}
</style>
<style scoped lang="scss">
.card_box {
  margin-top: 5px;
}

.card_button {
  margin-top: 20px;
  height: 10vh;
  border: none;
  display: flex;
  margin-left: 6vw;

  .el-card__body {
    & > .el-button {
      margin-left: 1vw;
    }
  }
}

.box-card_detail {
  height: 45vh;
}

.paddingStyle {
  /deep/ .el-card__body {
    padding: 0px !important;
  }
}

.dialog_commit {
  .el-form {
    .el-form-item {
      /deep/ .el-form-item__label {
        font-size: 2.5vh;
        line-height: 4vh;
      }

      .el-form-item__content {
        .el-input {
          /deep/ .el-input__inner {
            height: 5vh;
            font-size: 2.5vh;
          }
        }
      }
    }
  }
}

.ItemNumInfo {
  font-size: 6vh;
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
  align-items: center;
  color: #ff0000;
  margin-top: 2vh;
}

.ItemNumlabel {
  font-size: 3vh;
  margin-top: 1vh;
}

.ItemNumInfoDetail {
  font-size: 2.5vh;
  margin-top: 1.5vh;
  // border: 1px solid #CCCCCC;
}

.imageClass {
  .el-image {
    // &>img {
    /deep/ .el-image__inner {
      height: 80%;
      width: 38.9vh;
    }
  }
}

.buttonClass {
  width: 200px;
  height: 70px;
  font-size: 25px;
}

// .pagination {
// 	margin-top: 20px;
// 	text-align: right;
// }
// .el-form-item {
//     margin-bottom: 0px !important;
// }
// .el-form {
// 	display: flex;
// }
// 顶部扫描框
.headerInputClass {
  height: 11vh;

  /deep/ .el-input__inner {
    height: 100%;
    font-size: calc(100vh - 93vh);
    background-color: rgb(84, 105, 122);
    color: #ffffff;
  }

  /deep/ .el-input__inner::-webkit-input-placeholder {
    color: #ffffff;
  }
}

.el-message-box {
  .el-message-box__content {
    .el-message-box__container {
      .el-message-box__message {
        & > p {
          font-size: 25px;
        }
      }
    }
  }
}

// 卡片头部
/deep/ .el-card__header {
  padding: 8px 32px;
}

.clearfix:before,
.clearfix:after {
  display: table;
  content: "";
}

.clearfix:after {
  clear: both;
}
</style>
